package com.fmi.chesstern.interpreter;

import java.util.StringTokenizer;

import com.fmi.chesstern.interpreter.ParseObject.Action;

public class Parser {
	
	public static ParseObject parseCommand(String command) {
		ParseObject parseObject = new ParseObject();
		StringTokenizer tokenizer = new StringTokenizer(command);
		while (tokenizer.hasMoreElements()) {
			String token = tokenizer.nextToken();
			ParseType type = checkToken(token);
			if (type == ParseType.VERB) {
				Action action = Action.getAction(token);
				parseObject.setAction(action);
			} else if (type == ParseType.PARAM) {
				if (parseObject.getAction() == null || parseObject.getAction() == Action.FORFEIT ||
						parseObject.getAction() == Action.UNDO) {
					parseObject = null;
					break;
				}
				parseObject.addParameter(token);
			} else if (type == ParseType.UNKNOWN) {
				parseObject = null;
				break;
			}
		}	
		return parseObject;
	}
	
	private static ParseType checkToken(String token) {
		ParseType type = ParseType.UNKNOWN;
		if (token.equals("move") || token.equals("forfeit") || token.equals("undo")) {
			type = ParseType.VERB;
		} else if (token.length() == 2 
				&& isCorrectLetter(token.charAt(0)) && isCorrectIndex(token.charAt(1))) {
			type = ParseType.PARAM;
		}
		return type;
	}

	private static boolean isCorrectIndex(char charAt) {
		return charAt >= '0' && charAt <= '7';
	}

	private static boolean isCorrectLetter(char charAt) {
		return charAt >= 'a' && charAt <= 'h';
	}

	public enum ParseType {
		VERB, PARAM, UNKNOWN;
	}
	
}
